﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Grishko.DataTier.SqlSentence;
using OutdoorLib.BaseEntity.Filters;
using OutdoorLib.BaseEntity.Constraction;
using Grishko.DataTier;
using System.IO;

public partial class PriceListEditor : System.Web.UI.Page
{
    private List<EntitySingle> _Source = null;


    private List<EntitySingle> Source 
    { get 
        {
            if (null != _Source)
                        return _Source;

            if (null == FilterEditor.DataSource)
                            return new List<EntitySingle>();
            if (null == FilterEditor.DataSource())
                return null;

            _Source = FilterEditor.DataSource ().GetCollection();
               return _Source;

        } 
    }

    protected  IFilterEditor  FilterEditor { get { return (ctlFilterPanel1 as IFilterEditor  ); } }

    protected void Page_Load(object sender, EventArgs e)
    {
        FilterEditor.ImChange = FilterChanged;
        if (!IsPostBack)
        {
            MyDataBind();
        }
    }
    private void MyDataBind()
    {

        lvPriceList.DataSource = Source;
        DataBind();

    }

    private bool FilterChanged()
    {
        MyDataBind();
        updTable.Update();        
        ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), "HideAlert();", true);        
        return true;
    }
        

    private void SetFocus()
    {
        if (null == lvPriceList.EditItem)
            return;
        TextBox t = (TextBox)lvPriceList.EditItem.FindControl("txtCurrentPrice");
        t.Focus();
        
    }

    private bool UpdateItem()
    {
        try
        {
            HiddenField hf_C = (HiddenField)lvPriceList.EditItem.FindControl("hfConstractionID");
            HiddenField hf_S = (HiddenField)lvPriceList.EditItem.FindControl("hfSideID");
            TextBox t = (TextBox)lvPriceList.EditItem.FindControl("txtCurrentPrice");
            //найти конструкцию
            ConstractionEntity c = GetConstraction(hf_S.Value);                     
            // поправить в ней сумму стороны
            (c.SideList[hf_S.Value] as Side).CurrentPrice = Convert.ToInt32(t.Text);
            
            //найти сторонй поправить сумму - чтобы не перезапрашивать базу 
            GetSide(hf_S.Value).CurrentPrice = Convert.ToInt32(t.Text);

            Side s = GetSide(hf_S.Value).SideEntity;
            s.CurrentPrice = Convert.ToInt32(t.Text); 

            AppEnvironment.ObjectFactory.SaveObject(s);
            
            return true;
        }
        catch
        {
            return false;
        }
    }

    private ConstractionEntity GetConstraction(string SideID)
    { 
        for (int i=0;i<Source .Count ;i++)
        {
            if (Source[i].ID == SideID)
            {
                return (ConstractionEntity)(Source[i] as SideListPriceFilter.SideRow).Constraction;
 
            }
        }
        return null;
    }
    private OutdoorLib.BaseEntity.Filters.SideListFilter.SideRow  GetSide(string SideID)
    {
        for (int i = 0; i < Source.Count; i++)
        {
            if (Source[i].ID == SideID)
            {
                return ((OutdoorLib.BaseEntity.Filters.SideListFilter.SideRow)Source[i]);

            }
        }
        return null;
    }

    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
         
        if (string.Empty == e.CommandName) return;
        ListView lv = (ListView)sender;
        switch (lv.ID)
        {

            case "lvPriceList":
                //LvUpdCmd = UpdateItem;
                break;
        }

        switch (e.CommandName)
        {
            case "Edit":
                {
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;
                    MyDataBind();
                    SetFocus();
                    return;
                }
            case "Insert":
                {
                    break;
                }
            case "Update":
                {
                    if (UpdateItem())
                        lv.EditIndex = -1;
                    break;
                }
            case "Delete":
                {
                    break;
                }
        }

        MyDataBind();
    }

    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }
    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }

    #region PageMethod
    [System.Web.Services.WebMethod]
    public static string GetRowEditControl(string sValue,string RowID,bool IsEditState)
    {
        
        if (!IsEditState)
        {
            int v=0;
            if (!int.TryParse(sValue, out v))
            {
                return string.Empty;
            }
            
                    
            SecuretyContext SC = AppContext.GetSC();
            Side s = (Side)AppEnvironment.Helper.GetObject(RowID);
            s.CurrentPrice = Convert.ToInt32(sValue);
            AppEnvironment.ObjectFactory.SaveObject(s);

        }

        TextWriter sw = new StringWriter();
        Html32TextWriter w = new Html32TextWriter(sw);
        RowEditControl c = new RowEditControl() { FieldValue = sValue, RowID =RowID , IsEditState = IsEditState };
        c.RenderControl (w);
        return sw.ToString();        
    }
        


    protected string GetEditControl_obj(Int32 sValue, string RowID, bool IsEditState)
    {
        //return GetRowEditControl(sValue.ToString(), RowID, IsEditState);

        TextWriter sw = new StringWriter();
        Html32TextWriter w = new Html32TextWriter(sw);
        RowEditControl c = new RowEditControl() { FieldValue = sValue.ToString (), RowID = RowID, IsEditState = IsEditState };
        c.RenderControl(w);
        return sw.ToString();        
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    #endregion

    public class RowEditControl : Control
    {
        public string FieldValue { get; set; }
        public string RowID { get; set; }        
        public bool IsEditState { get; set; }
        protected override void Render(HtmlTextWriter writer)
        {
            Table tbl = new Table() { Width = new Unit("100%") };
           TableRow rw= new TableRow ();           
           rw.Cells.Add(new TableCell() { HorizontalAlign = HorizontalAlign.Left});
           rw.Cells.Add(new TableCell(){Width =new Unit ("20px")});           
           if (IsEditState)
           {
               TextBox t = new TextBox() { Text = FieldValue, Width =new Unit ("100%") };
               t.ID = RowID + "TextBox";               
               rw.Cells[0].Controls.Add(t);
               t.Text = FieldValue;
               

               Image btn = new Image();
               btn.ID = RowID + "Edit";
               btn.ImageUrl = "~/images/icon-save.gif";
               string[] p = {  RowID, t.ClientID};
               //rw.Cells[0].Attributes.Add("onClick", string.Format("SetRowEditControl('{0}','{1}');", p));
               btn.Attributes.Add("onClick", string.Format("SetRowEditControl('{0}','{1}');",p));
               rw.Cells[1].Controls.Add(btn);
           }
           else
           {
               rw.Cells[0].Text = FieldValue;

               Image btn = new Image();
               btn.ImageUrl = "~/images/icon-edit.gif";
               string[] p = { FieldValue, RowID, false.ToString() };
               btn.ID = RowID + "Show";
               rw.Cells[0].Attributes .Add("onClick", string.Format("GetRowEditControl('{0}', '{1}', true);", p));
               btn.Attributes .Add ("onClick", string.Format("GetRowEditControl('{0}', '{1}', true);", p));

               rw.Cells[1].Controls.Add(btn);
           }

          tbl.Rows .Add (rw); 
          tbl.RenderControl(writer);
        }
    }
}
